use warnings;
use strict;

sub ImdbApiOrg {
	my ($tt, $title, $edit, $re) = @_ ;
	my $record;
	my $errors = '';
	
	# fix lookup needs separate title and year
	my $year='';
	# $title may not include year
	my $short_title = $title; 
	# if it does
	if ($title =~ m!^(.+) (\d+)$!){ $short_title = $1; $year = $2; }
	
	
	# check for existing record - always needed in case no incomming tt
	open (RDB, "<$VAR{'DataDir'}/ppweb_tapiorg.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/ppweb_tapiorg.txt, $! (LI01)", 1, 0);
	while (<RDB>){
		if ($tt and m!^$tt [^\t]+\t(.+)!){
			$record = "$1\n";
			&Print ("Cached imdbapi.org record found for: $title (LI01)", 4, 0);
			last;
		}
		# allow for listing title w/ or w/o year
		elsif ($title and m!^(tt\d+) $title(?:[^\t]+)?\t(.+)!){
			$tt = $1;
			$record = "$2\n";
			&Print ("Cached imdbapi.org record found for: $title (LI01)", 4, 0);
			last;
		}
	}
	close RDB or warn $!;
	
	# get new or updated record
	if (!$record or $edit eq 'up'){ # don't enter if edit eq del or fixhttp://www.omdbapi.com/
		#&Print ("Fetching imdbapi.org record: $title (LI02)", 4, 0);
		require LWP::UserAgent;
		my $user_agent = LWP::UserAgent->new;
		$user_agent->agent("Mozilla/8.1");
		my $url;
# 		if ($tt){ $url = "http://imdbapi.com/?i=$tt&plot=full&tomatoes=true"; }
# 		elsif ($short_title and $year){ $url = "http://imdbapi.com/?t=$short_title&y=$year&plot=full&tomatoes=true"; }
		#if ($tt){ $url = "http://omdbapi.com/?i=$tt&plot=full&tomatoes=true"; }
		#elsif ($short_title and $year){ $url = "http://omdbapi.com/?t=$short_title&y=$year&plot=full&tomatoes=true"; }
		if ($tt){ $url = "http://imdbapi.org/?id=$tt&type=xml&plot=full&episode=0&lang=en-US"; }
		elsif ($short_title and $year){ $url = "http://imdbapi.org/?q=$short_title&year=$year&type=xml&plot=full&episode=0&lang=en-US"; }
		# imdbapi doesn't provide multiple returns, not using
		#else { $url = "http://imdbapi.com/?t=$short_title&plot=full&tomatoes=true"; }
		my $image_url;
		my $response = $user_agent->get($url);
			
		if ($response->is_success and $response->decoded_content) {
			$record = ''; # clear old record for updating
			my $xml = $response->decoded_content;
			if ($xml =~ m!<error>([^<]+)</error>!){ 
				$errors = "imdbapi.org response: $1";
				&Print ('imdbapi.org record fetch failed for: '.$title.' (LI02)', 3, 0);
			}
			else {
				my %data;
				$xml =~ s![{}]!!g;
				$xml =~ s!</item><item>!, !g;
				$xml =~ s!</?item>!!g;
				$xml =~ s!</?IMDBDocument>!!g;
				$xml =~ s!<\?xml version="1.0" encoding="utf-8"\?>!!g;
				if ($xml =~ m!<title>([^<]+)</title>!){ $data{'title'} = 'Title.....: '.$1.'<br>'."\t"; }
				else {$data{'title'} = '';}
				if ($xml =~ m!<also_known_as>([^<]+)</also_known_as>!){ $data{'also_known_as'} = 'AKA.......: '.$1.'<br>'."\t"; }
				else {$data{'also_known_as'} = '';}
	# 			if ($xml =~ m!<year>([^<]+)</year>!){ $data{'year'} = 'Year......: '.$1.'<br>'."\t"; }
	# 			else {$data{'year'} = '';}
				if ($xml =~ m!<release_date>(\d{4})(\d{2})(\d{2})</release_date>!){ $data{'release_date'} = 'Released..: '."$1-$2-$3<br>\t"; }
				else {$data{'release_date'} = '';}
				if ($xml =~ m!<country>([^<]+)</country>!){ $data{'country'} = 'Country...: '.$1.'<br>'."\t"; }
				else {$data{'country'} = '';}
				if ($xml =~ m!<language>([^<]+)</language>!){ $data{'language'} = 'Language..: '.$1.'<br>'."\t"; }
				else {$data{'language'} = '';}
				if ($xml =~ m!<rated>([^<]+)</rated>!){ $data{'rated'} = 'Rated.....: '.$1.'<br>'."\t"; }
				else {$data{'rated'} = '';}
				if ($xml =~ m!<genres>([^<]+)</genres>!){ $data{'genres'} = 'Genre.....: '.$1.'<br>'."\t"; }
				else {$data{'genres'} = '';}
				if ($xml =~ m!<directors>([^<]+)</directors>!){ 
					$data{'directors'} = $1;
					$data{'directors'} =~ s!([^\n]{55,65} )!$1<br>            !g;
					$data{'directors'} = 'Director..: '.$data{'directors'}.'<br>'."\t"; 
				}
				else {$data{'directors'} = '';}
				if ($xml =~ m!<writers>([^<]+)</writers>!){ 
					$data{'writers'} = $1;
					$data{'writers'} =~ s!([^\n]{55,65} )!$1<br>            !g;
					$data{'writers'} = 'Writer....: '.$data{'writers'}.'<br>'."\t"; 
				}
				else {$data{'writers'} = '';}
				if ($xml =~ m!<actors>([^<]+)</actors>!){ 
					$data{'actors'} = $1;
					$data{'actors'} =~ s!([^\n]{55,65} )!$1<br>            !g;
					$data{'actors'} = 'Actors....: '.$data{'actors'}.'<br>'."\t"; 
				}
				else {$data{'actors'} = '';}
				if ($xml =~ m!<runtime>([^<]+)</runtime>!){ $data{'runtime'} = 'Runtime...: '.$1.'<br>'."\t"; }
				else {$data{'runtime'} = '';}
				if ($xml =~ m!<rating>([^<]+)</rating>!){ $data{'rating'} = 'Rating....: '.$1.'<br>'."\t"; }
				else {$data{'rating'} = '';}
				if ($xml =~ m!<rating_count>([^<]+)</rating_count>!){ $data{'rating_count'} = 'Votes.....: '.$1.'<br>'."\t"; }
				else {$data{'rating_count'} = '';}
				if ($xml =~ m!<plot>([^<]+)</plot>!){ 
					$data{'plot'} = $1;
					$data{'plot'} =~ s!([^\n]{55,65} )!$1<br>            !g;
					$data{'plot'} = 'Plot......: '.$data{'plot'}.'<br><br>'."\t"; 
				}
				else {$data{'plot'} = '';}
				
				if ($xml =~ m!<poster>([^<]+)</poster>!){ 
					if ($1 ne 'N/A'){ $image_url=$1; }
				}
				if ($xml =~ m!<imdb_id>([^<]+)</imdb_id>!){ $tt=$1; }
				#elsif (m!^<type>([^<]+)</type>!){ $type=$1; } # M - Movie, TVS - TV Series, TV  - TV Movie, V   - Video, VG  - Video Game

				$record = "$tt $title\t$data{'title'}$data{'also_known_as'}$data{'release_date'}$data{'country'}$data{'language'}$data{'rated'}$data{'genres'}$data{'directors'}$data{'writers'}$data{'actors'}$data{'runtime'}$data{'rating'}$data{'rating_count'}$data{'plot'}"; 
				$record =~ s!<br>\t$!<br><br>\t$DateTime[2]\n!;
				
				if ($edit eq 'up'){
					local ($^I, @ARGV) = ('.bak', "$VAR{'DataDir'}/ppweb_tapiorg.txt");
					while(<>){
						if ($. == 1) { 
							print $record; # new and updated records
							unless (m!^$tt!){ print; } # replaced record on 1st line
						}
						elsif (m!^$tt!){ next; } # replaced record elsewhere
						else { print; }
					}
				}
				else {
					open (WDB, ">>$VAR{'DataDir'}/ppweb_tapiorg.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/ppweb_tapiorg.txt, $! (LI02)", 1, 0);
						print WDB $record;
					close WDB or warn $!;
				}
				$record =~ s!^[^\t]+\t!!; # remove leading id and title
				if ($edit eq 'up'){ $record = "Record Updated\n\n$record"; }
				&Print ('imdbapi.org record fetch successful for: '.$title.' (LI02)', 4, 0);
			}

# 				if ($tt){
# 					local ($^I, @ARGV) = ('.bak', "$VAR{'DataDir'}/ppweb_tapiorg.txt");
# 					while(<>){
# 						if ($. == 1) { 
# 							print $record; # new and updated records
# 							unless (m!^$tt!){ print; } # replaced record on 1st line
# 						}
# 						elsif (m!^$tt!){ next; } # replaced record elsewhere
# 						else { print; }
# 					}
# 					$record =~ s!^[^\t]+\t!!; # remove leading id and title
# 					if ($edit eq 'up'){ $record = "Record Updated\n\n$record"; }
# 				}
#			}
		}
		else { 
			&Print ('imdbapi.org record fetch failed: '.$response->status_line.' (LI03)', 1, 0); 
			$errors .= 'imdbapi.org record fetch failed: '.$response->status_line."\n";
		}
		
		# fetch image, if we don't have one
		if (-e "$VAR{'PPWebDir'}/images/$tt.jpg"){ &Print ('Using cached image (LI05)', 5, 0); }
		elsif ($image_url){# and !-e "$VAR{'PPWebDir'}/images/$tt.jpg"){
			#&Print ("Fetching IMDb image for: $title (LI02)", 4, 0);
			if ($image_url =~ m!jpg$!){
				$response = $user_agent->get($image_url, ':content_file' => "$VAR{'PPWebDir'}/images/$tt.jpg");
				unless ($response->is_success) {
					&Print ('IMDb image fetch failed: '.$response->status_line.' (LI04)', 1, 0);
					$errors .= 'IMDb image fetch failed: '.$response->status_line."\n";
				}
				else { 
					&Print ('IMDb image fetch successful: '.$tt.'.jpg (LI05)', 4, 0);
# 					my $convert = '';
# 					if ($convert = `which convert` and $convert =~ m!^/!){
# 					#if ($VAR{'ImdbApiImages'} eq 'convert'){
# 						chomp $convert;
# 						#my $ret = `$convert "$VAR{'PPWebDir'}/images/$tt.jpg" -resize '342>' "$VAR{'PPWebDir'}/images/$tt.tmp"`;
# 						if (system qx($convert '$VAR{'PPWebDir'}/images/$tt.jpg' -resize '342>' '$VAR{'PPWebDir'}/images/$tt.tmp')){
# 							&Delete ($VAR{'PPWebDir'}.'/images', $tt.'.jpg', 'LI05');
# 							&Save ($VAR{'PPWebDir'}.'/images', $tt, 'tmp', $VAR{'PPWebDir'}.'/images', $tt, 'jpg', 'LI05');
# 							&Print ('  Image resize successful: '.$tt.'.jpg (LI05)', 4, 0);
# 						}
# 						#if ($ret){ &Print ('convert returned: $ret (LI05)', 5, 0); }
# 					}
				}
			}
			# to let me know if not all images are .jpg
			else { &Print ("Image not a jpg: $image_url (LI05)", 1, 0); }
		}
		else { &Print ('No IMDb image available to fetch (LI05)', 4, 0); }
	}

	# delete image
	if ($edit eq 'img'){
		if (-e "$VAR{'PPWebDir'}/images/$tt.jpg"){ 
			&Delete ("$VAR{'PPWebDir'}/images", "$tt.jpg", 'LI07');
		}
	}
	# delete record
	if ($edit eq 'del'){
		if ($edit eq 'del'){
			&Print ("Deleting imdbapi.org record: $title (LI06)", 4, 0);
		}
		local ($^I, @ARGV) = ('.bak', "$VAR{'DataDir'}/ppweb_tapiorg.txt");
		while(<>){
			if ($. == 1) { 
				unless (m!^$tt!){ print; } # deleted or replaced record on 1st line
			}
			elsif (m!^$tt! and $edit){ next; } # deleted or replaced record elsewhere
			else { print; }
		}
		if (-e "$VAR{'PPWebDir'}/images/$tt.jpg"){ &Delete ("$VAR{'PPWebDir'}/images", "$tt.jpg", 'LI07'); }
		$record = "<pre><font face=\"Monospace,Courier,Courier New\">Record Deleted</font></pre></td></tr><tr><td>";
	}
	# process record
	elsif ($record){
		# IMDB link
		my $links = "<br>Links.....: <A HREF=\"http://www.imdb.com/title/$tt/\">IMDb</A></B>&nbsp;&nbsp;&nbsp;";
# 		# Rotten Tomatoes link - if available
# 		unless ($record =~ m!N/A<br><br>\t[^\t]+$!){
# 			my $rt = $tt;
# 			$rt =~ s!^tt(\d+)!<A HREF=\"http://www.rottentomatoes.com/alias?type=imdbid&s=$1\">Rotten Tomatoes</A>&nbsp;&nbsp;&nbsp;!;
# 			#$record =~ s!Rotten Tomatoes!$rt!;
# 			$links .= $rt;
# 		}
		# record update/delete links
		$links .= "Record:&nbsp;<a href=\"$VAR{'DbCgi'}?do=apiorg&amp;tt=$tt&amp;nt=$title&amp;db=up&amp;re=$re\">update</a>&nbsp;<a href=\"$VAR{'DbCgi'}?do=apiorg&amp;tt=$tt&amp;nt=$title&amp;db=del&amp;re=$re\">delete</a>&nbsp;Image:&nbsp;<a href=\"$VAR{'DbCgi'}?do=apiorg&amp;tt=$tt&amp;nt=$title&amp;db=img&amp;re=$re\">delete</a>";
		# add links to record
		$record =~ s!<br><br>\t([^\t]+)$!\n$links\n\n$1!;
		# replace all tabs and <br>'s with newline
		$record =~ s!<br>\t?!\n!g;
		# add pre container and image - if one exists, and td/tr close/start
		if (-e "$VAR{'PPWebDir'}/images/$tt.jpg"){
			$record = "<img SRC=\"$VAR{'PPWebUrl'}/images/$tt.jpg\" style=\"float:right\; padding-right:50px;\">\n<pre><font face=\"Monospace,Courier,Courier New\">$record\n</font></pre><br clear=\"all\"></td></tr><tr><td>\n";
		}
		elsif ($record =~ m!"Response":"Parse Error"!){
			$record = "<pre><font face=\"Monospace,Courier,Courier New\">The imdbapi.org site returned a 'Parse Error', try again later.</font></pre></td></tr><tr><td>";
		}
		else { $record = "<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre></td></tr><tr><td>"; }
	}
	else { $record = "<pre><font face=\"Monospace,Courier,Courier New\">Unable to fetch record\n\n$errors</font></pre></td></tr><tr><td>";}
	
	return $record;
	# other imdb options
	
# 	Name search (json): http://www.imdb.com/xml/find?json=1&nr=1&nm=on&q=jeniffer+garner
# 	Title search (xml): http://www.imdb.com/xml/find?xml=1&nr=1&tt=on&q=lost
# 	
# 	http://app.imdb.com/find?api=v1&appid=iphone1&locale=en_US&q=shrek
# 	It looks like all you need is q. 
}

1;